#include <audio/MIDI/MIDITrack.h>

namespace ne
{
    MIDITrack::MIDITrack(const std::string &name)
        : mName(name),
          mChannel(MIDI_CHANNEL0),
          mInstrument(MIDI_ACOUSTICGRANDPIANO),
          mHasNotes(false)
    {
    }

    void MIDITrack::setName(const std::string &name)
    {
        mName = name;
    }

    const std::string& MIDITrack::getName() const
    {
        return mName;
    }

    void MIDITrack::setChannel(const byte channel)
    {
        mChannel = channel;
    }

    byte MIDITrack::getChannel() const
    {
        return mChannel;
    }

    void MIDITrack::setInstrument(const byte instrument)
    {
        mInstrument = instrument;
    }

    byte MIDITrack::getInstrument() const
    {
        return mInstrument;
    }

    bool MIDITrack::hasNotes() const
    {
        return mHasNotes;
    }

    MIDIEvent* MIDITrack::getEvent(const double ticks) const
    {
        return 0;
    }

    MIDIEventListIterator MIDITrack::insertEvent(MIDIEvent *pEvent)
    {
        return mEventList.end();
    }

    void MIDITrack::pushBackEvent(MIDIEvent *pEvent)
    {
        if (pEvent)
        {
            if (mEventList.size() > 0)
            {
                pEvent->absoluteTicks = mEventList.back()->absoluteTicks + pEvent->relatedTicks;
            }
            else
            {
                pEvent->absoluteTicks = pEvent->relatedTicks;
            }
            mEventList.push_back(pEvent);
            if (pEvent->getType() == MIDI_NOTE_OFF ||
                pEvent->getType() == MIDI_NOTE_ON)
            {
                mHasNotes = true;
            }
        }
    }

    void MIDITrack::destroyAllEvents()
    {
        for (MIDIEventListIterator it=mEventList.begin(); it!=mEventList.end(); ++it)
        {
            delete (*it);
        }
        mEventList.clear();
    }

    MIDITrack::~MIDITrack()
    {
        destroyAllEvents();
    }
}
